import React, {useEffect, useRef, useState} from 'react';
import {Calendar, MapPin, Upload, Users, X} from 'lucide-react';
import {Req, UploadFile} from '../../util/fetch';

interface Training {
    id: number;
    title: string;
    subTitle: string;
    startDate: string;
    endDate: string;
    place: string;
    organizerId: string;
    organizerName: string;
    participants: number;
    views: number;
    status: '0' | '1' | '2';
    cover: string;
    tags?: string[];
    description: string;
    category: string;
}

// interface EditTrainingModalProps {
//     training: Training;
//     onClose: () => void;
//     onSave: (updatedTraining: Training) => void;
// }

const categories = [
    {id: 'dealer-meeting', name: '分销商会议'},
    {id: 'ice-sword', name: '寒冰亮剑'},
    {id: 'customer-thanks', name: '客户答谢会'},
    {id: 'new-year', name: '新春年会'},
    {id: 'spring-thunder', name: '春雷行动'},
    {id: '520-roadshow', name: '520路演'},
    {id: 'sunshine', name: '骄阳行动'},
    {id: 'target-sprint', name: '目标冲刺动员'}
];

const statusOptions = [
    {value: '0', label: '草稿'},
    {value: '1', label: '已发布'},
    {value: '2', label: '已完成'},
];

export default function EditTrainingModal({
                                              training,
                                              onClose,
                                              onSave
                                          }: any) {
    const [formData, setFormData] = useState<Training>({...training});
    const [userDropdown, setUserDropdown] = useState<any>([]);
    const fileInputRef = useRef<HTMLInputElement | null>(null); // 创建文件输入引用

    const queryUserList = async () => {
        const res = await Req(`/sysUser/list`)
        if (res.success) {
            setUserDropdown(res.data.map(item => {
                return {id: item.id, name: item.realname}
            }))
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryUserList()
    }, [])

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        const organizer = userDropdown.find(item => item.id === formData.organizerId)
        formData.organizerName = organizer?.name || ''
        onSave(formData);
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const {name, value} = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: value
        }));
    };

    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files) return;
        const res = await UploadFile(1, files[0])
        setFormData(prev => ({
            ...prev,
            'cover': res.data.url
        }));
        console.log('handleFileChange', files, res);
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
            <div className="bg-white rounded-lg w-full max-w-4xl mx-4 max-h-[90vh] flex flex-col">
                <div className="flex items-center justify-between p-4 border-b">
                    <h3 className="text-lg font-semibold text-gray-900">修改训练信息</h3>
                    <button onClick={onClose}>
                        <X className="w-6 h-6 text-gray-500"/>
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto p-6">
                    <form onSubmit={handleSubmit} className="space-y-6">
                        {/* 训练分类 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                训练分类 <span className="text-red-500">*</span>
                            </label>
                            <select
                                name="category"
                                defaultValue={formData.category}
                                onChange={handleChange}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                required
                            >
                                {categories.map(category => (
                                    <option key={category.id} value={category.id}>
                                        {category.name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        {/* 状态 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                状态 <span className="text-red-500">*</span>
                            </label>
                            <select
                                name="status"
                                defaultValue={formData.status}
                                onChange={handleChange}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                required
                            >
                                {statusOptions.map(option => (
                                    <option key={option.value} value={option.value}>
                                        {option.label}
                                    </option>
                                ))}
                            </select>
                        </div>

                        {/* 训练名称 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                训练名称 <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                name="title"
                                defaultValue={formData.title}
                                onChange={handleChange}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                required
                            />
                        </div>

                        {/* 副标题 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                副标题
                            </label>
                            <input
                                type="text"
                                name="subTitle"
                                defaultValue={formData.subTitle}
                                onChange={handleChange}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                        </div>

                        {/* 描述 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                描述
                            </label>
                            <textarea
                                name="description"
                                defaultValue={formData.description}
                                onChange={handleChange}
                                rows={4}
                                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                        </div>

                        {/* 封面图 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                封面图
                            </label>
                            <div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-lg">
                                {formData.cover ?
                                    (
                                        <img src={formData.cover} alt="封面图" className="w-21 h-21 rounded-lg"/>)
                                    : (
                                        <div className="space-y-1 text-center">
                                            <Upload className="mx-auto h-12 w-12 text-gray-400"/>
                                            <div className="flex text-sm text-gray-600">
                                                <label
                                                    htmlFor="cover-upload"
                                                    className="relative cursor-pointer rounded-md font-medium text-blue-600 hover:text-blue-500"
                                                >
                                                    <span>点击此处选择要上传的图片</span>
                                                    <input
                                                        id="cover-upload"
                                                        name="coverImage"
                                                        type="file"
                                                        className="sr-only"
                                                        accept="image/*"
                                                        ref={fileInputRef}
                                                        onChange={handleFileChange}
                                                    />
                                                </label>
                                                {/*<p className="pl-1">或拖拽图片到此处</p>*/}
                                            </div>
                                            <p className="text-xs text-gray-500">PNG, JPG, GIF 最大 10MB</p>
                                        </div>)
                                }
                            </div>
                        </div>

                        {/* 日期选择 */}
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    开始日期 <span className="text-red-500">*</span>
                                </label>
                                <div className="relative">
                                    <Calendar
                                        className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
                                    <input
                                        type="date"
                                        name="startDate"
                                        defaultValue={formData.startDate}
                                        onChange={handleChange}
                                        className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        required
                                    />
                                </div>
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    结束日期 <span className="text-red-500">*</span>
                                </label>
                                <div className="relative">
                                    <Calendar
                                        className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
                                    <input
                                        type="date"
                                        name="endDate"
                                        defaultValue={formData.endDate}
                                        onChange={handleChange}
                                        className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        required
                                    />
                                </div>
                            </div>
                        </div>

                        {/* 组织者 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                组织者 <span className="text-red-500">*</span>
                            </label>
                            <div className="relative">
                                {/*<User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>*/}
                                {/*<input*/}
                                {/*  type="text"*/}
                                {/*  name="organizerName"*/}
                                {/*  defaultValue={formData.organizerName}*/}
                                {/*  onChange={handleChange}*/}
                                {/*  className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"*/}
                                {/*  required*/}
                                {/*/>*/}
                                <select
                                    name="organizerId"
                                    defaultValue={formData.organizerId}
                                    onChange={handleChange}
                                    className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    required
                                >
                                    {userDropdown.map(user => (
                                        <option key={user.id} value={user.id}>
                                            {user.name}
                                        </option>
                                    ))}
                                </select>
                            </div>
                        </div>

                        {/* 参与人数 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                预计参与人数
                            </label>
                            <div className="relative">
                                <Users
                                    className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
                                <input
                                    type="number"
                                    name="participants"
                                    defaultValue={formData.participants}
                                    onChange={handleChange}
                                    className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    min="0"
                                />
                            </div>
                        </div>

                        {/* 地点 */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                地点 <span className="text-red-500">*</span>
                            </label>
                            <div className="relative">
                                <MapPin
                                    className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
                                <input
                                    type="text"
                                    name="location"
                                    defaultValue={formData.place}
                                    onChange={handleChange}
                                    className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    required
                                />
                            </div>
                        </div>
                    </form>
                </div>

                <div className="flex justify-end space-x-3 p-4 bg-gray-50 rounded-b-lg">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"
                    >
                        取消
                    </button>
                    <button
                        onClick={handleSubmit}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                    >
                        保存
                    </button>
                </div>
            </div>
        </div>
    );
}